#include <Windows.h>

#include <iostream>

#include "version_info.h"

version_info::version_info( const LPCTSTR file_path )
{
	//
	succeed_flag = false;
	// get file version information size
	DWORD version_info_hnd = 0UL;
	DWORD version_info_size =
		::GetFileVersionInfoSize(file_path, &version_info_hnd);
	//
	if (version_info_size){
		// allocate buffer for version info
		void *buffer = new char[version_info_size];
		// target version info pointer
		VS_FIXEDFILEINFO *sub_bolck;
		// get version info
		unsigned int sub_block_size;
		if (::GetFileVersionInfo(file_path, version_info_hnd, version_info_size, buffer)){
			if (::VerQueryValue(buffer, "\\", (void **)&sub_bolck, &sub_block_size)){
				// copy message
				value[0] = static_cast<unsigned short>(sub_bolck->dwProductVersionMS >> 16);
				value[1] = static_cast<unsigned short>(sub_bolck->dwProductVersionMS);
				value[2] = static_cast<unsigned short>(sub_bolck->dwProductVersionLS >> 16);
				value[3] = static_cast<unsigned short>(sub_bolck->dwProductVersionLS);
				// set flag
				succeed_flag = true;
			}
		}

		delete []buffer;
	}
}

std::ostream & operator<<( std::ostream &out, version_info &vi )
{
	if (vi.succeed_flag){
		out << vi.value[0] << "." << vi.value[1] << "." << vi.value[2]
		<< "." << vi.value[3];
	}
	else out << "?.?.?.?";

	return out;
}
